﻿using System.Collections.Generic;

namespace DapperExtensions.Sql
{
    public class PostgreSqlDialect : SqlDialectBase
    {
        public override string GetIdentitySql(string tableName)
        {
            return "SELECT LASTVAL() AS Id";
        }

        public override string GetPagingSql(string sql, int page, int resultsPerPage, IDictionary<string, object> parameters)
		{
			int startValue = (page-1) * resultsPerPage;
            return GetSetSql(sql, startValue < 0 ? 0 : startValue, resultsPerPage, parameters);
		}
		
		public override string GetSetSql(string sql, int firstResult, int maxResults, IDictionary<string, object> parameters)
		{
			string result = string.Format("{0} LIMIT {1}maxResults OFFSET {1}pageStartRowNbr", sql,ParameterPrefix);
			parameters.Add($"{ParameterPrefix}maxResults", maxResults);
			parameters.Add($"{ParameterPrefix}pageStartRowNbr", firstResult);
			return result;
		}
        public override char ParameterPrefix
        {
            get { return '@'; }
        }
        public override string GetColumnName(string prefix, string columnName, string alias)
        {
#pragma warning disable S125 // Sections of code should not be commented out
            return base.GetColumnName(prefix, columnName?.ToLower(), alias?.ToLower());//.ToLower();
#pragma warning restore S125 // Sections of code should not be commented out
        }

        public override string GetTableName(string schemaName, string tableName, string alias)
        {
#pragma warning disable S125 // Sections of code should not be commented out
            return base.GetTableName(schemaName?.ToLower(), tableName?.ToLower(), alias?.ToLower());//.ToLower();
#pragma warning restore S125 // Sections of code should not be commented out
        }
        public override string GetOperatorString(Operator Operator, bool Not)
        {
            return Operator switch
            {
                Operator.Ag => Not ? "<@" : "@>",
                Operator.Gt => Not ? "<=" : ">",
                Operator.Ge => Not ? "<" : ">=",
                Operator.Lt => Not ? ">=" : "<",
                Operator.Le => Not ? ">" : "<=",
                Operator.Like => Not ? "NOT ILIKE" : "ILIKE",
                _ => Not ? "<>" : "=",
            };
        }
    }

}
